package com.fau.wmbj.server.service.impl;

import cn.dev33.satoken.secure.BCrypt;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.fau.wmbj.server.entity.User;
import com.fau.wmbj.server.service.UserService;
import com.fau.wmbj.server.service.base.BaseServiceImpl;
import com.fau.wmbj.server.utils.Filter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 用户-service
 *
 * @author jiawei
 * @version 1.0
 * @datetime 2024-02-26 17:49
 */
@Slf4j
@Service
public class UserServiceImpl extends BaseServiceImpl<User, Long> implements UserService {

    @Override
    public User getCurrentUser() {
        String tokenValue = StpUtil.getTokenValue();
        String loginId = (String) StpUtil.getLoginIdByToken(tokenValue);
        if (loginId != null) {
            return super.find(Long.valueOf(loginId));
        }
        return null;
    }

    @Override
    public SaTokenInfo login(User user) throws Exception {
        String username = user.getUsername();
        String password = user.getPassword();
        User user1 = super.findEntity(Filter.eq("email", username));
        if (StringUtils.isBlank(username) || user1 == null) {
            throw new Exception("用户名或密码错误");
        }
        String encryptedPassword = user1.getEncryptedPassword();
        boolean checkpw = BCrypt.checkpw(password, encryptedPassword);
        if (!checkpw) {
            throw new Exception("用户名或密码错误");
        }
        StpUtil.login(user1.getId(), user.getRememberMe());
        return StpUtil.getTokenInfo();
    }

    @Override
    public List<Long> selectUserIdsByRoleIds(List<Long> groupIds) {

        return List.of();
    }
}
